#include "DXUT.h"
#include "EntityItem.h"
#include "../World.h"


EntityItem::EntityItem(Item * item, const D3DXVECTOR3& pos) : Entity(pos) {
	m_Item		= item;
}

EntityItem::EntityItem(Item * item, const D3DXVECTOR3& pos, const D3DXVECTOR3& velo) : Entity(pos) {
	m_Item		= item;
	m_Velocity	= velo;
}

EntityItem::~EntityItem() {
	SAFE_DELETE( m_Item );
}


Item * EntityItem::getItem() {
	return m_Item;
}

void EntityItem::OnFrameMove( EntityWorld * pWorld, double fTime, float fElapsedTime) {
	Entity::OnFrameMove(pWorld, fTime, fElapsedTime);

	if (!m_Grounded)
	{ // Mid-air = falling
		m_Velocity.y -= fElapsedTime * 40.0f;
	}
	else
	{
		//m_Velocity.x -= min(abs(m_Velocity.x),abs(m_Velocity.x - (fElapsedTime * 0.5)))*(m_Velocity.x<0?-1:1);
		//m_Velocity.z -= min(abs(m_Velocity.z),abs(m_Velocity.z - (fElapsedTime * 0.5)))*(m_Velocity.z<0?-1:1);
		m_Velocity.y = 5.0f;
	}

	
	m_Rotation.y += fElapsedTime;
}

#ifdef RENDER
void EntityItem::OnD3D11CreateDevice( ID3D11Device* pd3dDevice ) {
	BlockVertex *   vertices	= NULL;
	WORD			vs			= 0;
	WORD *			indices		= NULL;
	WORD			is			= 0;

	m_Item->GenerateIndexed(&vertices, &vs, &indices, &is);

	D3DXMATRIX mMat;
	D3DXMatrixScaling(&mMat, 0.3f, 0.3f, 0.3f);
	for (int i = 0; i < vs; i++)
		D3DXVec3TransformCoord(&vertices[i].Pos, &vertices[i].Pos, &mMat);

	D3D11_BUFFER_DESC bd;
	ZeroMemory( &bd, sizeof(bd) );
	bd.Usage = D3D11_USAGE_DEFAULT;
	bd.ByteWidth = sizeof( BlockVertex ) * vs;
	bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	bd.CPUAccessFlags = 0;
	D3D11_SUBRESOURCE_DATA InitData;
	ZeroMemory( &InitData, sizeof(InitData) );
	InitData.pSysMem = vertices;
	pd3dDevice->CreateBuffer( &bd, &InitData, &m_pVertexBuffer11 );

	bd.Usage = D3D11_USAGE_DEFAULT;
	bd.ByteWidth = sizeof( WORD ) * is;        // 36 vertices needed for 12 triangles in a triangle list
	bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
	bd.CPUAccessFlags = 0;
	InitData.pSysMem = indices;
	pd3dDevice->CreateBuffer( &bd, &InitData, &m_pIndexBuffer11 );

	m_indexSize = is;

	free(vertices);
	free(indices);
}
#endif